package be.vdab.gwt.cultuurhuis.client.widgets.utils;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasChangeHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusListener;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class EditableLabel extends Composite implements HasText, HasChangeHandlers {

	private static EditableLabelUiBinder uiBinder = GWT
			.create(EditableLabelUiBinder.class);

	interface EditableLabelUiBinder extends UiBinder<Widget, EditableLabel> {
	}

	public EditableLabel() {
		initWidget(uiBinder.createAndBindUi(this));
	}
			
	public EditableLabel(String string) {
		this();
		this.setText(string);
	}

	@UiField Label label;
	@UiField TextBox textbox;
	
	boolean inEditMode = false;
	
	@UiHandler("label") 
	public void onLabelclick(ClickEvent e){
		// It is not expected to click the label when in editable mode. Consider throwing an exception when that happens.
		if(!inEditMode){
			textbox.setText(label.getText());
			label.setVisible(false);
			textbox.setVisible(true);
			this.textbox.setFocus(true);
			
			this.inEditMode = true;			
		}
	}
	@UiHandler("textbox") 
	public void onTextboxFocus(BlurEvent e){
		// It is not expected to click the label when not in editable mode. Consider throwing an exception when that happens.
		if(inEditMode){			
			label.setText(textbox.getText());
			label.setVisible(true);
			textbox.setVisible(false);
			
			this.inEditMode = false;			
		}
	}

	@Override
	public String getText() {
		return this.label.getText();
	}

	@Override
	public void setText(String text) {
		this.label.setText(text);		
	}

	@Override
	public HandlerRegistration addChangeHandler(ChangeHandler handler) {		
		return this.textbox.addChangeHandler(handler);
	}


}
